from django.core.paginator import Paginator
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger
from django.http import JsonResponse
from django.forms.models import model_to_dict
from commodity.models import Types, CommodityInfos

def get_page_data(ojb, p, page_count=10):
    '''
    封装Django内置分页功能
    :param ojb:分页对象，数据类型：列表或模型对象
    :param p:页数，获取当前页数所对应的数据
    :param page_count:每页数据量，默认是一页有10行数据
    :return:
    '''
    previous, next = 0, 0
    ps = Paginator(ojb, page_count, 0)
    try:
        pages = ps.get_page(p)
    except PageNotAnInteger:
        # 如果参数p的数据类型不是整型，就返回第一页数据
        pages = ps.get_page(1)
    except EmptyPage:
        # 若用户访问的页数大于实际页数，则返回最后一页的数据
        pages = ps.get_page(ps.num_pages)
    # 上一页和下一页的页数
    if pages.has_previous():
        previous = pages.previous_page_number()
    if pages.has_next():
        next = pages.next_page_number()
    count = ps.count
    # 将分页对象转为列表格式返回
    pages = pages.object_list
    return pages, previous, next, count

def commodityView(request):
    '''
    商品列表API
    '''
    types = request.GET.get('types', '')
    search = request.GET.get('search', '')
    sort = request.GET.get('sort', 'sold')
    p = request.GET.get('p', 1)
    context = {'state': 'success', 'msg': '获取成功', 'data': {}}
    context['data']['types'] = []
    firsts = Types.objects.values_list('firsts', flat=True).distinct()
    for f in firsts:
        t = Types.objects.filter(firsts=f).values_list('seconds', flat=True).all()
        context['data']['types'].append(dict(name=f, value=list(t)))
    cf = CommodityInfos.objects.all()
    if types:
        cf = cf.filter(types=types)
    if sort:
        cf = cf.order_by('-' + sort)
    if search:
        cf = cf.filter(name__contains=search)
    result = []
    for c in cf.all():
        d = model_to_dict(c)
        d['created'] = c.created.strftime('%Y-%m-%d')
        d['img'] = c.img.url
        d['details'] = c.details.url
        result.append(d)
    pages, previous, nexts, pageCount = get_page_data(result, p)
    context['data']['commodityInfos'] = dict(data=pages, previous=previous,
                                             next=nexts, count=cf.count(),
                                             pageCount=pageCount)
    return JsonResponse(context, json_dumps_params={'ensure_ascii': False}, safe=False)
